<template>
  <header>
    <div class="header-left">
      <i class="iconfont icon-a-farfa-sun sun-icon"></i>
      <p>新中地天气</p>
      <h4>{{ city }}</h4>
      <span v-if="weatherData">实时天气：{{ weatherData.weather }} {{ weatherData.temperature }}℃</span>
      <span v-if="weatherData">{{ weatherData.windpower }}级 {{ weatherData.winddirection }}风</span>
    </div>
    <div class="header-right">
      <i class="iconfont icon-fa-circle-info-fill info-icon" @click="showInfoModal = true"></i>
      <i v-if="showAddButton" class="iconfont icon-jiahao" @click="addCity"></i>
    </div>
    <div class="info-modal" v-if="showInfoModal">
      <div class="modal-content">
        <h2>关于：</h2>
        <p>这个应用可以用来追踪你选择城市的当前天气</p>
        <h2>如何使用:</h2>
        <p>
          1.点击搜索框输入你希望追踪的城市<br />
          2.在搜索结果中选中一个城市，你将获取当地最新的天气<br />
          3.点击右侧的＋号可以将追踪城市的天气情况保存在首页
        </p>
        <h2>移除城市:</h2>
        <p>
          如果你不想在首页关注某个城市,可以通过底部的按钮删<br>
          除它
        </p>
        <button @click="showInfoModal = false">关闭</button>
      </div>
    </div>
  </header>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { getWeather } from '../api/weatherApi';

const route = useRoute();
//控制弹窗信息
const showInfoModal = ref(false);
//控制城市名称
const city = ref('');
//控制武汉当天天气
const weatherData = ref(null);
//控制加号显示
const showAddButton = ref(true); // 控制加号显示


// 检查是否已保存当前城市
const checkSaved = () => {
  try {
    const savedData = localStorage.getItem('savedCities');
    // 安全解析
    let cities = [];
    if (savedData) {
      try {
        cities = JSON.parse(savedData);
        if (!Array.isArray(cities)) cities = [];
      } catch (e) {
        cities = [];
      }
    }

    const currentAdcode = route.params.adcode;
    // 只有在详情页且adcode存在时才判断按钮显示
    if (currentAdcode) {
      showAddButton.value = !cities.some(c => c.adcode === currentAdcode);
    } else {
      showAddButton.value = false; // 在首页不显示加号
    }
    return cities;
  } catch (error) {
    console.error('解析保存的城市数据失败:', error);
    return []; // 返回空数组作为默认值
  }
};

// 点击加号，进行城市添加
const addCity = async () => {

    const data2 = await getWeather(route.params.adcode);
    console.log(data2);
    
    try {
      // 先从localStorage获取数据，确保是一个数组
      let saved = [];
      const savedStr = localStorage.getItem('savedCities');
      // 安全解析JSON
      if (savedStr) {
        try {
          saved = JSON.parse(savedStr);
          if (!Array.isArray(saved)) saved = [];
        } catch (e) {
          saved = [];
        }
      }

      // 创建城市数据对象
      const cityData = {
        name:data2.city,
        adcode: route.params.adcode,
        temp: data2.temperature
      };
      console.log(cityData);
      // 添加到数组并保存
      saved.push(cityData);
      localStorage.setItem('savedCities', JSON.stringify(saved));

      showAddButton.value = false;
      window.dispatchEvent(new Event('storage-update')); // 触发数据更新事件
    } catch (error) {
      console.error('添加城市失败:', error);
      // 初始化一个新数组
      localStorage.setItem('savedCities', '[]');
    }
  };

  // 监听路由变化
  watch(() => route.params, checkSaved);
  //刷新渲染页面
  onMounted(async () => {
    const data = await getWeather('420100');
    console.log(data);
    if (data) {
      weatherData.value = data;
      city.value = data.city;
    }

    checkSaved();
  });
</script>

<style lang="scss" scoped>
header {
  display: flex;
  justify-content: space-between;
  padding: 1.5rem 250px;
  align-items: center;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
  background: #00668a;
  color: white;
  position: relative;

  .header-left {
    display: flex;
    align-items: center;
    gap: 1rem;

    p {
      font-size: 1.5rem;
    }

    h4 {
      font-size: 1.125rem;
      line-height: 1.75rem;
      font-weight: inherit;
    }

    span {
      font-size: 0.875rem;
      line-height: 1.25rem;
    }

    .sun-icon {
      font-size: 24px;
      color: #ffd700;
      animation: rotate 20s linear infinite;
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 1rem;
    // 太阳图标的样式


    // 信息图标的样式
    .info-icon {
      font-size: 20px;
      color: #ffffff;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: scale(1.2);
        color: #004e71;
      }
    }

    .icon-jiahao {
      font-size: 20px;
      color: #ffffff;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: scale(1.2);
        color: #004e71;
      }
    }
  }





  // 信息弹窗样式
  .info-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;

    .modal-content {
      background-color: rgb(255 255 255);
      padding: 1rem;
      opacity: 1;
      align-self: flex-start;
      border-radius: 8px;
      max-width: 500px;
      margin-top: 8rem;
      color: black;

      h2 {
        margin: 0;
        font-size: inherit;
        font-weight: inherit;
      }

      p {
        font-size: .75rem;
        line-height: 1rem;
        margin-bottom: 1rem;
        margin: 0 0 16px;
      }

      button {
        margin-top: 1rem;
        padding: 0.5rem 2rem;
        background-color: #00668a;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 0.75rem;
        transition: all 0.3s ease;

        &:hover {
          background-color: #005275;
        }
      }
    }
  }
}

// 太阳旋转动画
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>